from datetime import date, datetime, timedelta
import time

from django.contrib.auth.models import AnonymousUser

from users.models import User
from django.utils.deprecation import MiddlewareMixin

MAX_REQUEST_PER_SECOND = 2  # 每秒访问次数


def login_middleware(get_response):
    # 此处编写的代码仅在Django第一次配置和初始化的时候执行一次

    def middleware(request):
        # 此处编写的代码会在每个请求处理视图前被调用

        response = get_response(request)

        # 此处编写的代码会在每个请求处理视图之后被调用
        # now_date = date.today()
        # now_date = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        # now_date = datetime.now() + timedelta(hours=8)
        now_date = datetime.now()
        user = request.user
        if isinstance(user, AnonymousUser) or user is None:  # 不是匿名用户与数据库交互保存访问时间
            return response
        else:
            # user = User.objects.get(username=user)
            user.last_login = now_date
            user.save()
            return response

    return middleware


class IPLimitedMiddleware(MiddlewareMixin):
    '''ip访问限制'''

    def process_request(self, request):
        now = time.time()
        request_queue = request.session.get('request_queue', [])
        if len(request_queue) < MAX_REQUEST_PER_SECOND:
            request_queue.append(now)
            request.session['request_queue'] = request_queue
        else:
            time0 = request_queue[0]
            if (now - time0) < 1:
                time.sleep(5)

            request_queue.append(time.time())
            request.session['request_queue'] = request_queue[1:]
